
package net.anzix.jimposition.transformations;

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import javax.swing.JPanel;
import net.anzix.jimposition.*;
import org.apache.log4j.Logger;

public class RotateFilter extends BasicTransformation{
    Logger logger = Logger.getLogger(RotateFilter.class);
    private RotateFilterPanel panel = new RotateFilterPanel();
    
    public byte[] alter(byte[] input) {
        try {
            //input
            PdfReader inputReader = new PdfReader(input);
            //output
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            
            
            String degree = getAttribute("degree").toString();
            logger.debug("Degree: "+ degree);
            int pages = (Integer)getAttribute("pages");
            logger.debug("pages: "+ pages);
            //setting new page size
            
            Document document = new Document();
            
            //get writer
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            PdfContentByte cb=null;
            
            
            
            int pagenum=1;
            int maxPageNum = inputReader.getNumberOfPages();
            for (int page=1;page<maxPageNum;page++){
                //rotate is necessary
                Rectangle pageSize;
                Rectangle oldPageSize = inputReader.getPageSize(page);
                if (isRotateNecessary(page,pages) && (degree.equals("270") || degree.equals("90"))){
                    pageSize = new Rectangle(
                            oldPageSize.height(),
                            oldPageSize.width()
                            );
                } else {
                    logger.debug("don't rotate");
                    pageSize = inputReader.getPageSize(page);
                }
                //rotate is not necessary
                //if yes
                document.setPageSize(pageSize);
                if (cb==null) {
                    document.open();
                    cb = writer.getDirectContent();
                    
                } else {
                    document.newPage();
                }
                if (!isRotateNecessary(page,pages)){
                    cb.addTemplate(writer.getImportedPage(inputReader, page),1.0f,0f,0f,1.0f,0f,0f);
                } else {
                    double angle = Math.toRadians(Float.parseFloat(degree));
                    float offsetX,offsetY;
                    if (degree.equals("90")){
                        offsetX = oldPageSize.bottom() + oldPageSize.height();
                        offsetY = -1 * oldPageSize.left();
                    } else if (degree.equals("180")){
                        offsetX = 2 * pageSize.left() + pageSize.width();
                        offsetY = 2 * pageSize.bottom() + pageSize.height();
                    } else if (degree.equals("270")){
                        offsetX = -1 * oldPageSize.bottom();
                        offsetY = oldPageSize.left() + oldPageSize.width();
                    } else {
                        offsetX=0;
                        offsetY=0;
                    }
                    cb.addTemplate(writer.getImportedPage(inputReader, page),
                            (float) (Math.cos(angle)),
                            (float) (Math.sin(angle)),
                            (float) (-1 * Math.sin(angle)),
                            (float) (Math.cos(angle)),
                            offsetX,
                            offsetY
                            );
                }
                
                
                for (int i=0;i<1000;i+=100){
                    PdfTemplate template = cb.createTemplate(100, 100);
                    
                    // we add some graphics
                    template.moveTo(0, 0);
                    template.lineTo(100, 100);
                    template.moveTo(0, 100);
                    template.lineTo(100, 0);
                    template.stroke();
                    template.setRGBColorStrokeF(255f, 0f, 0f);
                    template.circle(50f, 50, 10f);
                    template.stroke();
                    
                    // we add some text
                    template.beginText();
                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    template.setFontAndSize(bf, 12);
                    template.setTextMatrix(100, 100);
                    template.showText(i+"X"+i);
                    template.endText();
                    
                    // we add the template on different positions
                    cb.addTemplate(template, i, i);
                }
                
                cb.stroke();
            }
            document.close();
            return outputStream.toByteArray();
        }catch(DocumentException ex){
            ex.printStackTrace();
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        
    }
    public JPanel getPanel() {
        return panel;
    }
    public String toString() {
        return "Rotate pages";
    }
    private boolean isRotateNecessary(int pageNum, int pages){
        if (pages==0) return true;
        else if (pages == 1 && pageNum % 2 == 1) return true;
        else if (pages == 2 && pageNum % 2 == 0) return true;
        else return false;
    }
    
    public void setPanelSettings() {
        
    }
    
    public void getPanelSettings() {
        setAttribute("degree",panel.getDegreeComboBox().getSelectedItem());
        setAttribute("pages",panel.getPageComboBox().getSelectedIndex());
    }
    
}

